package com.bwstudio.common.response;

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Result implements Serializable{

	private static final long serialVersionUID = 1L;

	private boolean success;

	private String code;

	private String msg;

	/**
	 * 只有当非null时才进行序列化到前端，
	 * 例如：服务端错误时，不希望服务端的异常栈信息暴露到前端，在Result.fail响应中没有包含data，没有必要让data输出null到前端
	 */
	@JsonInclude(Include.NON_NULL)
	private Object data;

	public static Result success() {
		Result result = new Result();
		result.setSuccess(true);
		result.setResultCode(BasicErrorCodeEnum.SUCCESS);
		return result;
	}

	public static Result success(Object data) {
		Result result = new Result();
		result.setSuccess(true);
		result.setResultCode(BasicErrorCodeEnum.SUCCESS);
		result.setData(data);
		return result;
	}

	public static Result failure(ErrorCodeI resultCode) {
		Result result = new Result();
		result.setSuccess(false);
		result.setResultCode(resultCode);
		return result;
	}

	public static Result failure(ErrorCodeI resultCode, Object data) {
		Result result = new Result();
		result.setSuccess(false);
		result.setResultCode(resultCode);
		result.setData(data);
		return result;
	}


	/**
	 * @Description: 暂时封闭这个方法，如果要自定义错误响应，必须用枚举类或实现类来实现统一响应接口 {@link com.bwstudio.common.unires.response.IResponseCode}
	 * @param code
	 * @param message
	 * @return
	 * @Author: Bu Wei
	 * @Date: 2020年3月13日 上午10:32:04
	 */
//	public static Result failure(Integer code, String message) {
//		Result result = new Result();
//		result.setCode(code);
//		result.setMsg(message);
//		return result;
//	}

	private void setResultCode(ErrorCodeI code) {
		this.code = code.getCode();
		this.msg = code.getMessage();
	}
}
